package com.jc.service.h5;

import com.alibaba.fastjson.JSONObject;
import com.jc.common.util.ExceptionUtil;
import com.jc.common.util.HttpUtil;
import com.jc.common.util.MD5;
import com.jc.ds.base.service.BaseServiceException;
import com.jc.ds.model.SupplierLogisticsCompany;
import com.jc.ds.model.Xorder;
import com.jc.framework.enums.*;
import com.jc.service.jctask.JcTaskService;
import com.jc.service.logisticscompany.LogisticsCompanyService;
import com.jc.service.model.h5.H5RespModel;
import com.jc.service.model.h5.ShopConfig;
import com.jc.service.order.XorderService;
import com.jc.service.supplierlogisticscompany.SupplierLogisticsCompanyService;
import com.jc.service.systemloglist.SystemLogListService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SuppressWarnings("all")
@Service
public class ShopServiceImpl implements ShopService {

private final Logger LOGGER = LoggerFactory.getLogger(ShopServiceImpl.class);
	private Long ts = new Date().getTime();
	@Autowired
	private SystemLogListService  systemLogListService;
	
	@Autowired
	SupplierLogisticsCompanyService supplierLogisticsCompanyService;
	
	@Value("${jingxi.h5.url}")
	private String baseurl;
	@Value("${jingxi.h5.code}")
	private String code;
	@Value("${jingxi.h5.key}")
	private String key;


	@Override
	public H5RespModel pushH5(String url,String body) {
		H5RespModel retMode = new H5RespModel();
		
		boolean isOK = false;
		String ret = null;
		try {
			url = baseurl + url;
			
			ret = HttpUtil.postJson(url, body, null);
			JSONObject retObject = JSONObject.parseObject(ret);
			if(retObject != null) {
				retMode.setReturnCode(retObject.getString("returnCode"));
				retMode.setReturnMsg(retObject.getString("returnMsg"));
				if(StringUtils.equals("0", retObject.getString("returnCode"))) {
					isOK = true;
				}
			}else {
				isOK = false;
				retMode.setReturnCode("1");
				retMode.setReturnMsg("向H5商城推送失败, 返回值为空!");
			}
			
			if(isOK) {
				systemLogListService.addSystemLog(body, Conclusion.OK, "", LogType.PUSH_H5_PRODUCT, ret);
			}else {
				systemLogListService.addSystemLog(body, Conclusion.FAIL, retObject == null ? "" : retObject.getString("returnMsg") , LogType.PUSH_H5_PRODUCT, ret);
			}
			return retMode;
		}catch (Exception e) {
			LOGGER.error("推送H5过程中出现网络错误, {},{}" , e.getMessage(),e);
			retMode.setReturnCode("1");
			if(e != null && StringUtils.isNotBlank(e.getMessage())) {
				retMode.setReturnMsg("推送失败 : " + StringUtils.substring(e.getMessage(), 0,150));
			}
			systemLogListService.addSystemLog(body, Conclusion.FAIL, ExceptionUtil.subExceptionMessage(e, 0, 200) , LogType.PUSH_H5_PRODUCT, ret);
			return retMode;
		}
	}


	@Override
	public H5RespModel pushH5(String url, Map<String,Object> body,LogType logType) {
		H5RespModel retMode = new H5RespModel();
		boolean isOK = false;
		String ret = null;
		try {
			url = baseurl + url;
			//拼接请求参数字符串
			body.put("code", code);
			body.put("encryptedString", MD5.passmd5("code="+code+"&ts="+String.valueOf(ts)+"&key="+key));
			body.put("ts",ts);
			ret = HttpUtil.post(url, body);
			JSONObject retObject = JSONObject.parseObject(ret);
			if(retObject != null) {
				retMode.setReturnCode(retObject.getString("returnCode"));
				retMode.setReturnMsg(retObject.getString("returnMsg"));
				if(StringUtils.equals("0", retObject.getString("returnCode"))) {
					isOK = true;
				}
			}else {
				isOK = false;
				retMode.setReturnCode("1");
				retMode.setReturnMsg("向H5商城推送失败, 返回值为空!");
			}

			if(isOK) {
				systemLogListService.addSystemLog(JSONObject.toJSONString(body), Conclusion.OK, "",logType, ret);
			}else {
				systemLogListService.addSystemLog(JSONObject.toJSONString(body), Conclusion.FAIL, retObject.getString("returnMsg") ,logType, ret);
			}
			return retMode;
		}catch (Exception e) {
			LOGGER.error("推送H5过程中出现网络错误, {},{}" , e.getMessage(),e);
			retMode.setReturnCode("1");
			if(e != null && StringUtils.isNotBlank(e.getMessage())) {
				retMode.setReturnMsg("推送失败 : " + StringUtils.substring(e.getMessage(), 0,150));
			}
			systemLogListService.addSystemLog(JSONObject.toJSONString(body), Conclusion.FAIL, ExceptionUtil.subExceptionMessage(e, 0, 200) , logType, ret);
			return retMode;
		}
	}


	@Override
	public ShopConfig getShopConfig(){
		ShopConfig shopConfig = new ShopConfig();
		shopConfig.setURL(baseurl);
		shopConfig.setCODE(code);
		shopConfig.setKEY(key);
		return shopConfig;
	}

	@Autowired
	private LogisticsCompanyService logisticsCompanyService;
	@Autowired
	private XorderService xorderService;
	@Autowired
	private JcTaskService jcTaskService;

	/**
	 * 商城订单id
	 * */
	@Override
	public String pushOrder(String orderShopid) {
		Xorder xorder = new Xorder();
		xorder.setChannelOrderId(String.valueOf(orderShopid));
		List<Xorder> xorders = xorderService.queryAll(xorder);
		if (CollectionUtils.isEmpty(xorders)){
			throw new BaseServiceException("订单不存在");
		}
		if (xorders.size()>1){
			throw new BaseServiceException("订单存在多条"+orderShopid);
		}
		xorder = xorders.get(0);
		if(StringUtils.isBlank(xorder.getExpressName())) throw new BaseServiceException("该条订单未找到物流单号 ， 请检查! ");
		SupplierLogisticsCompany supplierLogisticsCompany = new SupplierLogisticsCompany();
		supplierLogisticsCompany.setShopChannel(ChannelSource.APPV1.getName());
		supplierLogisticsCompany.setSupplierSn(xorder.getSupplierId());
		supplierLogisticsCompany.setSupplierLogisticsName(xorder.getExpressName());
		List<SupplierLogisticsCompany> logisticsCompanies = supplierLogisticsCompanyService.queryAll(supplierLogisticsCompany);
		if(CollectionUtils.isEmpty(logisticsCompanies)) {
			jcTaskService.addTask(TaskType.push_express,String.valueOf(xorder.getId()),"", Booleans.FALSE,xorder.getExpressName() + " 未找到匹配的物流公司");
			return "1";
		}
		//推送到商城
		Map<String,Object> paramH5 = new HashMap<>();
		paramH5.put("channelOrderId",orderShopid);
		paramH5.put("courierId",logisticsCompanies.get(0).getShopLogisticsCode());
		paramH5.put("courierNumber",xorder.getExpressNo());
		//请求商城第三方
		System.out.println("推送订单===="+paramH5);
		H5RespModel h5RespModel = this.pushH5(ThirdPartyParam.PUSH_ORDER_H5.getName(), paramH5,LogType.PUSH_H5_LOGISTICS);
		String returnCode = h5RespModel.getReturnCode();
		if ("1".equals(returnCode)){
			jcTaskService.addTask(TaskType.push_express,String.valueOf(xorder.getId()),JSONObject.toJSONString(paramH5), Booleans.FALSE,h5RespModel.getReturnMsg());
		}else{
			jcTaskService.addTask(TaskType.push_express,String.valueOf(xorder.getId()),JSONObject.toJSONString(paramH5), Booleans.TRUE,h5RespModel.getReturnMsg());
		}
		return returnCode;
	}
	
	
	
	public H5RespModel pushInventory(Long skuCode,String inventory) {
		
		Map<String,Object> pushMap = new HashMap<String,Object>();
		pushMap.put("skuCode", skuCode.toString());
		pushMap.put("inventory", inventory);
		H5RespModel ret = pushH5(ThirdPartyParam.UPDATE_PRO_H5.getName(),pushMap,LogType.PRO_NUM_PUSH_SHOP);
		
		if(ret != null && StringUtils.equals("0", ret.getReturnCode())) {
			jcTaskService.addTask(TaskType.push_product_inventory_update,"" + skuCode,JSONObject.toJSONString(pushMap), Booleans.TRUE,ret.getReturnMsg());
		}else {
			jcTaskService.addTask(TaskType.push_product_inventory_update,"" + skuCode,JSONObject.toJSONString(pushMap), Booleans.FALSE,ret.getReturnMsg());
		}
		
		
		return ret;
	}

}
